import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import Layouts from '@/components/Layout';
import bannerImg from '../../../../public/images/defprof-bg.jpg';
import { Avatar, Empty, Pagination, Spin, Tabs, Tag } from 'antd';
import Tour from '@/components/Tour';
import Activity from '@/components/Activity';
import { history, useParams } from 'umi';
import { getUserDetailInfo } from '@/service/api/user';
import { UserInfo } from '@/types/user';
import configs from '../../../../config/env';
import { ActivityList, ActivitySearch, TourList, TourSearch } from '@/types/touractivity';
import { getActivityList, getTourList } from '@/service/api/touractivity';
const FeedDetail: React.FC = () => {
  const params: { id: string } = useParams();
  const firstUpload = useRef(true); // 记录是否是首次加载页面
  const [userDetailInfo, setUserDetailInfo] = useState<UserInfo | null>(null);
  const [tourListLoading, setTourListLoading] = useState<boolean>(false);
  const [tourList, setTourList] = useState<TourList[]>([]);
  const [searchTourQuery, setSearchTourQuery] = useState<TourSearch>({
    pageNum: 1,
    pageSize: 9,
    userId: Number(params.id) ?? null,
  });
  const [tourListTotal, setTourListTotal] = useState<number>(0);
  const [actListLoading, setActListLoading] = useState<boolean>(false);
  const [actList, setActList] = useState<ActivityList[]>([]);
  const [actListTotal, setActListTotal] = useState<number>(0);
  const [searchActQuery, setSearchActQuery] = useState<ActivitySearch>({
    pageNum: 1,
    pageSize: 9,
    userId: Number(params.id) ?? null,
  });
  const getUserDetailInfoData = async () => {
    const { id: userId } = params;
    const { data }: { data: UserInfo } = await getUserDetailInfo({
      userId,
    });
    setUserDetailInfo(data);
  };
  const handleChangePageTour = (page: number, pageSize: number) => {
    setSearchTourQuery({
      pageNum: page,
      pageSize,
      userId: Number(params.id),
    });
  };
  const getTourListDataByUserId = async () => {
    try {
      setTourListLoading(true);
      const { rows, total }: { rows: TourList[]; total: number } = await getTourList(
        searchTourQuery,
      );
      setTourList(rows);
      setTourListTotal(total);
    } finally {
      setTourListLoading(false);
    }
  };
  const handleChangePageAct = (page: number, pageSize: number) => {
    setSearchActQuery({
      pageNum: page,
      pageSize,
      userId: Number(params.id),
    });
  };
  const getActivityListDataByUserId = async () => {
    try {
      setActListLoading(true);
      const { rows, total }: { rows: ActivityList[]; total: number } = await getActivityList(
        searchActQuery,
      );
      setActList(rows);
      setActListTotal(total);
    } finally {
      setActListLoading(false);
    }
  };
  const onChange = (key: string) => {
    if (key === 'item-1') {
      setSearchTourQuery((searchTourQuery) => ({ ...searchTourQuery, pageNum: 1 }));
    } else if (key === 'item-2') {
      setSearchActQuery((searchActQuery) => ({ ...searchActQuery, pageNum: 1 }));
    }
  };
  useEffect(() => {
    // 如果详情id不能转成数字的话就证明是用户在路径随便输入的字符串
    if (!isNaN(Number(params.id))) {
      getUserDetailInfoData();
    } else {
      history.push('/404');
    }
  }, []);
  useEffect(() => {
    getTourListDataByUserId();
  }, [searchTourQuery]);
  useEffect(() => {
    if (firstUpload.current) {
      // 首次加载不执行
      firstUpload.current = false;
      return;
    }
    getActivityListDataByUserId();
  }, [searchActQuery]);
  const tabContent1 = (
    <div>
      <Spin tip="正在玩命加载..." size="large" spinning={tourListLoading}>
        <div className="tab1_content">
          {tourList.map((item) => (
            <Tour
              key={item.id}
              title={item.title}
              id={item.id}
              time={item.time}
              price={item.price}
              remark={item.remark}
              userInfo={item.user}
              bacImg={item.bacImg}
              tags={item.tags}
            ></Tour>
          ))}
        </div>
      </Spin>
      <div className="pagination_wrapper">
        {tourListTotal !== 0 && (
          <Pagination
            current={searchTourQuery.pageNum}
            total={tourListTotal}
            showTitle
            pageSize={searchTourQuery.pageSize}
            showSizeChanger={false}
            onChange={handleChangePageTour}
          />
        )}
        {!tourListLoading && tourListTotal === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>
    </div>
  );
  const tabContent2 = (
    <div>
      <Spin tip="正在玩命加载..." size="large" spinning={actListLoading}>
        <div className="tab1_content">
          {actList.map((item) => (
            <Activity
              key={item.id}
              id={item.id}
              country={item.country}
              remark={item.describes}
              userInfo={item.user}
              imgUrl={item.imgUrl}
              title={item.title}
              tags={item.tags}
              city={item.city}
            ></Activity>
          ))}
        </div>
      </Spin>

      <div className="pagination_wrapper">
        {actListTotal !== 0 && (
          <Pagination
            current={searchActQuery.pageNum}
            total={actListTotal}
            showTitle
            pageSize={searchActQuery.pageSize}
            showSizeChanger={false}
            onChange={handleChangePageAct}
          />
        )}
        {!actListLoading && actListTotal === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>
    </div>
  );
  const items = [
    { label: '主办旅游', key: 'item-1', children: tabContent1 }, // 务必填写 key
    { label: '探险活动', key: 'item-2', children: tabContent2 },
  ];
  const tl = () => {
    return (
      <div className="feed_user_banner">
        {/* 此处banner图为动态，应用户自己上传 没有就默认这个 */}
        <img src={bannerImg} alt="" />
        <div className="user_avatar">
          <Avatar
            size={200}
            src={
              userDetailInfo?.avatar
                ? configs[process.env.API_ENV as any].API_SERVER + userDetailInfo?.avatar
                : '/images/cat.e69c9c17.jpg'
            }
          />
        </div>
      </div>
    );
  };
  return (
    <Layouts tl={tl()}>
      <div className="user_info_wrapper">
        <div className="user_info">
          <div className="user_name">{userDetailInfo?.nickName}</div>
          <div className="user_loaction">
            {userDetailInfo?.country}， {userDetailInfo?.city}
          </div>
          <div>
            {userDetailInfo?.tags &&
              userDetailInfo?.tags.split(',').map((item: string, index: number) => (
                <Tag
                  key={index}
                  className="hobby_tag"
                  onClick={() => {
                    window.open('/feed?tag=' + item);
                  }}
                >
                  {item}
                </Tag>
              ))}
          </div>
          <div className="user_remark">{userDetailInfo?.remark}</div>
        </div>
      </div>
      <Tabs items={items} defaultActiveKey="item-1" onChange={onChange} />
    </Layouts>
  );
};
export default FeedDetail;
